﻿using UnityEngine;

namespace Script
{
    public class NodeSquare
    {
        /// <summary>
        /// 节点在地图中的位置
        /// </summary>
        public MapPosIndex mapPos;

        /// <summary>
        /// 预制件的引用
        /// </summary>
        public GameObject view { get; set; }

        /// <summary>
        /// 方块在地图中的一维索引值
        /// </summary>
        public int mapIdx { get; private set; }

        private readonly RectTransform viewRect;


        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="res">预制件的资源</param>
        /// <param name="trans">父节点</param>
        public NodeSquare(GameObject res)
        {
            view = GameObject.Instantiate(res);
            view.transform.SetParent(GameObject.Find("UIViewGame/Bg/MapNode").transform);
            viewRect = view.GetComponent<RectTransform>();
        }

        /// <summary>
        /// 刷新该节点的位置
        /// </summary>
        /// <param name="x">横轴位置</param>
        /// <param name="y">纵轴位置</param>
        public void RefreshPositionByValue(int x, int y)
        {
            mapPos.x = x;
            mapPos.y = y;
            RefreshPosition();
        }

        public void MoveDown()
        {
            mapPos.y--;
            RefreshPosition();
        }

        public void MoveRight()
        {
            mapPos.x++;
            RefreshPosition();
        }

        public void MoveLeft()
        {
            mapPos.x--;
            RefreshPosition();
        }

        private void RefreshPosition()
        {
            var cor_x = (mapPos.x - 0.5f) * Constant.CellWidth;
            var cor_y = (mapPos.y - 0.5f) * Constant.CellWidth;
            viewRect.anchoredPosition = new Vector2(cor_x, cor_y);

            mapIdx = mapPos.x + (mapPos.y - 1) * Constant.MapWidth;
        }

        /// <summary>
        /// 提前检测该单元格向下移动一次后，在地图上的一维索引
        /// </summary>
        /// <returns>地图上的一维索引</returns>
        public int PreCheckMoveDownIndex()
        {
            return mapPos.x + (mapPos.y - 1 - 1) * Constant.MapWidth;
        }

        public bool CheckSquareCanMove(int addX, int addY)
        {
            var cor_x = mapPos.x + addX;
            var cor_y = mapPos.y + addY;
            if (cor_x < 1 || cor_x > Constant.MapWidth || cor_y < 1 || cor_y > Constant.MapHeight)
            {
                return false;
            }

            return true;
        }
    }
}